Imports DaveSexton.DocProject.DocSites

Partial Public Class DocSite
	Inherits System.Web.UI.MasterPage

	Public Shared ReadOnly ProjectTitle As String = My.Application.Info.Title
	Public Shared ReadOnly ProjectCompany As String = My.Application.Info.CompanyName
	Public Shared ReadOnly ProjectCopyright As String = My.Application.Info.Copyright

	Public ReadOnly Property Sidebar() As DocSiteSidebar
		Get
			Return sideBarControl
		End Get
	End Property

	Public ReadOnly Property CurrentTopicTitle() As String
		Get
			Dim topic As String = sideBarControl.TableOfContents.SelectedTopic

			If String.IsNullOrEmpty(topic) Then
				topic = sideBarControl.TableOfContents.DefaultTopic
			Else
				Dim topicNameIndex As Integer = topic.LastIndexOf(CChar("/"))

				If topicNameIndex > -1 AndAlso topic.Length > topicNameIndex + 1 Then
					topic = topic.Substring(topicNameIndex + 1)
				End If
			End If

			Return topic
		End Get
	End Property

	Private robotsMeta As HtmlMeta

	Protected Function GetPersistSidebarHandleScript() As String
		Return "<script type=""text/javascript"">" & _
			"var enablePersistSidebarHandle = " & _
			DocSiteManager.Settings.SidebarHandlePersisted.ToString().ToLowerInvariant() & _
			";</script>"
	End Function

	Public Function AddMetaTag(ByVal name As String, ByVal content As String) As HtmlMeta
		Dim meta As New HtmlMeta
		meta.Name = name
		meta.Content = content

		Page.Header.Controls.Add(meta)

		Return meta
	End Function

	Public Sub RemoveMetaTag(ByVal meta As HtmlMeta)
		Page.Header.Controls.Remove(meta)
	End Sub

	Public Sub EnsureRobotsMetaTag(ByVal noindex As Boolean, ByVal nofollow As Boolean)
		If robotsMeta Is Nothing Then
			If noindex OrElse nofollow Then
				robotsMeta = AddMetaTag("ROBOTS", CreateRobotsMetaTagContent(noindex, nofollow))
			End If
		ElseIf Not noindex AndAlso Not nofollow Then
			RemoveMetaTag(robotsMeta)
		Else
			robotsMeta.Content = CreateRobotsMetaTagContent(noindex, nofollow)
		End If
	End Sub

	Private Shared Function CreateRobotsMetaTagContent(ByVal noindex As Boolean, ByVal nofollow As Boolean) As String
		Dim content As New System.Text.StringBuilder(17)

		If noindex Then
			content.Append("NOINDEX")
		End If

		If nofollow Then
			If noindex Then
				content.Append(", ")
			End If

			content.Append("NOFOLLOW")
		End If

		Return content.ToString()
	End Function

	Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
		MyBase.OnPreRender(e)

		If TypeOf Context.CurrentHandler Is IDocSiteDefault Then
			Page.Title = String.Format(System.Globalization.CultureInfo.CurrentCulture, Page.Title, ProjectTitle, CurrentTopicTitle)
		End If
	End Sub

End Class